package com.sa.app.utilities;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.support.v4.app.Fragment;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
import com.sa.app.R;
import com.sa.app.fragments.MapFragment;

public class CustomizedOverlay extends ItemizedOverlay {

	private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
	private Context mContext;
	private MyApplication mApplication;
	private Fragment f;

	public CustomizedOverlay(Drawable defaultMarker, Context context,
			Application mApplication, Fragment f) {
		super(boundCenterBottom(defaultMarker));
		this.mContext = context;
		this.mApplication = (MyApplication) mApplication;
		this.f = f;

	}

	@Override
	protected OverlayItem createItem(int i) {
		return mOverlays.get(i);
	}

	@Override
	public int size() {
		return mOverlays.size();
	}

	public void addOverlay(OverlayItem overlay) {
		mOverlays.add(overlay);
		populate();
	}

	@Override
	protected boolean onTap(int index) {
		if (f instanceof MapFragment) {
			renameRegion(index);
		}

		return true;
	}

	private void renameRegion(int index) {

		final OverlayItem item = mOverlays.get(index);
		final GeoPoint gp = item.getPoint();
		AlertDialog.Builder builder = new AlertDialog.Builder(mContext)
		.setTitle(mContext.getString(R.string.titleNewNameRegion))
		.setMessage(mContext.getString(R.string.msgNewNameRegion));

		final EditText input = new EditText(mContext);
		builder.setView(input);

		builder.setPositiveButton(mContext.getString(R.string.ok),
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String newName = input.getText().toString();
				if (!newName.equals("")) {
					String s = "UPDATE regions SET name='" + newName
							+ "' WHERE latitude=" + gp.getLatitudeE6()
							+ " AND longitude=" + gp.getLongitudeE6();
					mApplication.getDataBase().query(s);
					mOverlays.remove(item);
					mOverlays.add(new OverlayItem(item.getPoint(), item
							.getTitle(), item.getSnippet()));

					((MapFragment) f).update(mOverlays);

				} else {
					Toast.makeText(
							mContext,
							mContext.getString(R.string.invalid_region),
							Toast.LENGTH_LONG).show();
				}

			}
		});
		builder.setNegativeButton(mContext.getString(R.string.cancel),
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Canceled.
			}
		});
		builder.show();
	}

}
